import { message } from 'antd';
import axios, { AxiosRequestConfig } from 'axios';
import { getToken } from './auth';

export interface Response<T> {
  code: number;
  data: T;
  message: string;
}

export const axiosInstance = axios.create({
  baseURL: 'http://127.0.0.1:8001',
  timeout: 5000,
})

axiosInstance.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers!.token = token
    }
    return config
  },
  (error) => {
    console.error('error', error)
    message.error('网络异常')
    return Promise.reject(error)
  },
)

axiosInstance.interceptors.response.use(
  (response) => {
    return Promise.resolve(response)
  },
  (error) => {
    return Promise.reject(error)
  },
)

export default function request<T = any>(config: AxiosRequestConfig): Promise<Response<T>> {
  return new Promise((resolve, reject) => {
    axiosInstance.request(config).then((res) => {
      resolve(res.data)
    }).catch((error) => {
      reject(error)
    })
  })
}
